//
//  HTSearchView.swift
//  weibo
//
//  Created by JonsonLiu on 16/4/17.
//  Copyright © 2016年 liujonson. All rights reserved.
//

import UIKit

class HTSearchView: UIView {

    
    @IBOutlet weak var searchTextfed: UITextField!
    
    @IBOutlet weak var canlenlButton: UIButton!
    
    @IBOutlet weak var right: NSLayoutConstraint!
    
    class func searchView() -> HTSearchView {
        
        return NSBundle.mainBundle().loadNibNamed("HTSearch", owner: nil, options: nil).last! as! HTSearchView
    }
    
    
    // 以代码的时候去创建控件，就会走这个方法
    override init(frame: CGRect) {
        super.init(frame: frame)
    }
    
    // 从xib里面唤醒
    // 里面的子控件全部连线完毕
    override func awakeFromNib() {
        print("awakeFromNib")
        // 设置 leftView
        leftView.frame.size = CGSize(width: self.frame.height, height: self.frame.height)
        searchTextfed.leftView = leftView
        searchTextfed.leftViewMode = .Always
        
        
         //通过代码的形式设置边框
                searchTextfed.layer.borderWidth = 1
                searchTextfed.layer.borderColor = UIColor.redColor().CGColor
                searchTextfed.layer.cornerRadius = 5
                searchTextfed.layer.masksToBounds = true
    }
    
    
    // 当控件从 xib 里面加载的话，就会走这个方法
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    
    @IBAction func beginEditing(sender: UITextField) {
        // 执行约束的动画效果：
        // 1. 改约束
        self.right.constant = self.canlenlButton.frame.width
        // 2. 把重新布局的代码放到动画代码块里面
        UIView.animateWithDuration(0.25) { () -> Void in
            // 重新布局
            self.layoutIfNeeded()
        }
        print("开始编辑了哈哈")
    }
    
    /// 取消按钮点击
    ///
    /// - parameter sender: <#sender description#>
    @IBAction func cancelButtonClick(sender: UIButton) {
        // 1 更改约束
        self.right.constant = 0
        // 2. 执行动画
        UIView.animateWithDuration(0.25) { () -> Void in
            // 重新布局
            self.layoutIfNeeded()
        }
        // 3. 取消第一响应者
        self.searchTextfed.resignFirstResponder()
    }
    
    // MARK: - 懒加载控件
    
    private lazy var leftView: UIImageView = {
        let imageView = UIImageView(image: UIImage(named: "searchbar_textfield_search_icon"))
        // 设置内容模式
        imageView.contentMode = .Center
        return imageView
    }()
    


}
